package com.mybook.app.filter;


import com.mybook.app.core.BaseResponse;
import com.mybook.app.error.Error;
import com.mybook.app.utils.JsonUtil;
import com.mybook.app.utils.Logger;
import com.mybook.app.core.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.sleuth.Span;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * * 类注释
 *
 * @author: shenwei
 * @date: 2017/6/15
 * @time: 10:04
 * @see: 链接到其他资源
 * @since: 1.0
 * <p>
 * <p>
 * 判断 session
 * <p>
 * 首先判断这个接口需不要session
 * <p>
 * 不需要直接到过滤
 * <p>
 * 需要的，要做过滤，判断session是否过期
 */
@WebFilter(urlPatterns = "/*")
public class BasicTokenFilter implements Filter {

    public static final String MINA_ON_LOGIN = "/mina/onLogin";
    @Value("${web.expireTime}")
    private Long expireTime;

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        long curTime = System.currentTimeMillis();
        String url = httpServletRequest.getServletPath();
        Logger.info(this, "---查询路径URL---" + url + " ， 请求方法 ：" + httpServletRequest.getMethod());
        Object object = MDC.get(Span.TRACE_ID_NAME);
        String tranceId = (object == null ? "" : object.toString());

        Cookie tanceCookie = new Cookie("tranceId", tranceId);
        tanceCookie.setMaxAge(httpServletRequest.getSession().getMaxInactiveInterval());
        httpServletResponse.addCookie(tanceCookie);

        // 获取请求头信息
        String userId = httpServletRequest.getHeader("userId");
        // 假如用户请求头Id为空，抛出对应的错误码
        if (StringUtils.isBlank(userId) && !MINA_ON_LOGIN.equalsIgnoreCase(url)) {
            BaseResponse baseResponse = BaseResponse.fail(Error.NOT_EXIST_USER_IN_HEAD.getCode(), Error.NOT_EXIST_USER_IN_HEAD.getMessage());
            this.setResponseData(httpServletResponse, JsonUtil.toJsonString(baseResponse));
            return;
        }

        UserContext.init(userId);
        try {
            chain.doFilter(httpServletRequest, httpServletResponse);
        } finally {
            UserContext.clean();
        }
        return;
    }

    @Override
    public void destroy() {
        Logger.info(this, "---destroy BasicTokenFilter---");
    }

    /**
     * 设置结果值
     *
     * @param httpServletResponse
     * @param result
     * @throws IOException
     */
    public void setResponseData(HttpServletResponse httpServletResponse, String result) throws IOException {
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.print(result);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

}


